package org.example.simplemanagementsystem.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.example.simplemanagementsystem.mapper.EmpExprMapper;
import org.example.simplemanagementsystem.mapper.EmpMapper;
import org.example.simplemanagementsystem.pojo.Emp;
import org.example.simplemanagementsystem.pojo.EmpExpr;
import org.example.simplemanagementsystem.pojo.EmpQueryParam;
import org.example.simplemanagementsystem.pojo.PageResult;
import org.example.simplemanagementsystem.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Array;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

@Service
public class EmpServiceImpl implements EmpService {
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private EmpExprMapper empExprMapper;
    @Override
    public PageResult page(EmpQueryParam empQueryParam) {
        PageHelper.startPage(empQueryParam.getPage(), empQueryParam.getSize());

        List<Emp> empList = empMapper.list(empQueryParam);

        Page<Emp> p = (Page<Emp>) empList;

        return new PageResult(p.getTotal(), p.getResult());
    }

    @Override
    @Transactional
    public void save(Emp emp) {
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.insert(emp);
        // 保存工作经历信息
        Integer empId = emp.getId();
        List<EmpExpr> exprList = emp.getExprList();
        if(!CollectionUtils.isEmpty(exprList)){
            exprList.forEach(empExpr -> empExpr.setEmpId(empId));
            empExprMapper.insertBatch(exprList);
        }
    }

    @Override
    @Transactional
    public void deleteByIds(List<Integer> ids) {
        // 1. 删除员工的基本信息
        empMapper.deleteByIds(ids);
        // 2. 删除员工的工作经历
        empExprMapper.deleteByEmpIds(ids);
    }

    @Override
    public Emp getInfo(Integer id) {
        return empMapper.getById(id);
    }

    @Override
    @Transactional
    public void update(Emp emp) {
        // 1. 根据ID更新员工基本信息
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.updateById(emp);
        // 2. 根据员工ID删除员工的工作经历信息
        empExprMapper.deleteByEmpIds(Arrays.asList(emp.getId()));
        // 3. 新增员工的工作经历
        Integer empId = emp.getId();
        List<EmpExpr> exprList = emp.getExprList();
        if(!CollectionUtils.isEmpty(exprList)){
            exprList.forEach(empExpr -> empExpr.setEmpId(empId));
            empExprMapper.insertBatch(exprList);
        }
    }

    @Override
    public List<Emp> getList() {
        return empMapper.getList();
    }
}
